#include "PositionControllerComponent.h"
#include "GameObjectSystem.h"
#include "KeyboardInputManager.h"
#include "PositionControllerProperty.h"
#include "position.h"

const StringHash PositionControllerComponent::POSITION_CONTROLLER_ID= StringHash("posController");

PositionControllerComponent::PositionControllerComponent()
	:Component(POSITION_CONTROLLER_ID, 0)
{
}

PositionControllerComponent::~PositionControllerComponent()
{
}

void PositionControllerComponent::update(real frametime, real timestep)
{
	GameObjectSystem& gameObjectSystem= GameObjectSystem::GetSingleton();
	if(gameObjectSystem.isInPause())
	{
		return;
	}
	KeyboardInputManager& keyboardInputManager= KeyboardInputManager::GetSingleton();
	const ObjectPropertyTable* propertyTable= gameObjectSystem.getProperties(PositionControllerProperty::POSITION_CONTROLLER_PROPERTY_ID);
	if(propertyTable != NULL)
	{
		for(ObjectPropertyTable::const_iterator opIt= propertyTable->begin(); opIt != propertyTable->end(); ++opIt)
		{
			const PositionControllerProperty* positionController= static_cast<const PositionControllerProperty*>(opIt->second);
			ObjectProperty* positionProperty= gameObjectSystem.editProperty(Position::POSITION_ID, positionController->getObjectId());
			if(positionProperty != NULL)
			{
				Position* position= static_cast<Position*>(positionProperty);
				matrix matPos= position->getPosition();
				if( positionController->AIControlled() ) {
					vector3 translation;
					GetTranslation(matPos, &translation);
					if(m_aiHelper->shouldMoveDown(positionController->getObjectId()) && translation.y > -82)
					{
						//matrix matTranslation;
						AddTranslation(&matPos, vector3(0.f, -1.f, 0.f));
						position->setPosition(matPos);
					}
					else if(m_aiHelper->shouldMoveUp(positionController->getObjectId()) && translation.y < 82)
					{
						AddTranslation(&matPos, vector3(0.f, 1.f, 0.f));
						position->setPosition(matPos);
					}
				}
				else if(keyboardInputManager.getKeyState(positionController->getUp()) == 0 || keyboardInputManager.getKeyState(positionController->getDown()) == 0)
				{
					vector3 translation;
					GetTranslation(matPos, &translation);
					if( keyboardInputManager.getKeyState(positionController->getUp()) > 0 && translation.y > -82)
					{
						//matrix matTranslation;
						AddTranslation(&matPos, vector3(0.f, -1.f, 0.f));
						position->setPosition(matPos);
					}
					else if(keyboardInputManager.getKeyState(positionController->getDown()) > 0 && translation.y < 82)
					{
						AddTranslation(&matPos, vector3(0.f, 1.f, 0.f));
						position->setPosition(matPos);
					}
				}
			}
		}
	}
}
